<script setup lang="ts">
import { reactive, ref, defineProps, watch, computed } from "vue";
import {
  delAllHistoryApi,
  getHistoryListApi,
  batchHistoryApi,
  updateHistoryApi
} from "@/api/call-history";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { NetState } from "@/utils/utils";

const props = defineProps({
  // 用以通知当前组件，该字段变化时重新请求接口
  timestamp: {
    type: [String, Number],
    default: ""
  }
});

// 点名历史
const historyList = ref([]);
const listTotal = ref(0);
const listQuery = reactive({
  page: 1,
  size: 20
});
const getHistoryList = async function () {
  const { data } = await getHistoryListApi(listQuery);
  const list = data.list || [];
  const total = data.total || 0;

  list.forEach(item => {
    item.create_time = dayjs(item.create_time).format("YYYY-MM-DD hh:mm");
  });

  historyList.value = list;
  listTotal.value = total;
};
const changePagination = function (page) {
  listQuery.page = page;
  getHistoryList();
};

const sizeChange = function (size) {
  listQuery.size = size;
  listQuery.page = 1;
  getHistoryList();
};

getHistoryList();

watch(
  () => props.timestamp,
  () => getHistoryList()
);

const cleanBtnDisabled = computed(() => {
  return !historyList.value.length;
});

const delAllHistory = function () {
  ElMessageBox.confirm(`清除后将不可恢复，确认清除？`, {
    title: "确认清除",
    type: "warning"
  })
    .then(() => {
      return delAllHistoryApi();
    })
    .then(res => {
      if (res.code === NetState.Success) {
        ElMessage.success(`历史点名记录已清除`);
        getHistoryList();
      }
    });
};

// 批量删除
const multipleSelection = ref([]);
const batchDisabled = computed(() => {
  return !multipleSelection.value.length;
});
const handleSelectionChange = function (val) {
  multipleSelection.value = val;
};
const batchDelHistory = function () {
  const selectionIdList = multipleSelection.value.map(item => item.history_id);
  ElMessageBox.confirm(`是否确认删除？`, {
    title: "确认删除",
    type: "warning"
  })
    .then(() => {
      const param = {
        history_id_list: selectionIdList
      };
      return batchHistoryApi(param);
    })
    .then(res => {
      if (res.code === NetState.Success) {
        ElMessage.success("删除成功");

        // 若当前无数据则自动跳到上一页
        if (
          selectionIdList.length >= historyList.value.length &&
          listQuery.page > 1
        ) {
          listQuery.page--;
        }
        getHistoryList();
      }
    });
};

const changeAbsent = function (isAbsent, row) {
  const param = {
    history_id: row.history_id,
    is_absent: isAbsent
  };
  updateHistoryApi(param);
};
</script>

<template>
  <div class="history-page">
    <div class="page-container-head">
      <ElButton
        type="danger"
        :disabled="cleanBtnDisabled"
        @click="delAllHistory"
        >清除历史记录</ElButton
      >
      <ElButton type="danger" :disabled="batchDisabled" @click="batchDelHistory"
        >删除</ElButton
      >
    </div>
    <div class="table-box">
      <ElTable
        :data="historyList"
        row-key="history_id"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="30" />
        <ElTableColumn label="时间" prop="create_time" min-width="140" />
        <ElTableColumn label="学生" prop="stu_name" />
        <ElTableColumn label="班级" prop="class_name" />
        <ElTableColumn label="缺勤" align="center">
          <template #default="{ row }">
            <div :class="{ absent: true, [`absent-${row.is_absent}`]: true }" />
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="60" align="center" fixed="right">
          <template #default="{ row }">
            <ElSwitch
              v-model="row.is_absent"
              inline-prompt
              active-text="已到"
              inactive-text="缺勤"
              :active-value="0"
              :inactive-value="1"
              style="
                --el-switch-on-color: #67c23a;
                --el-switch-off-color: #f56c6c;
              "
              @change="changeAbsent($event, row)"
            />
          </template>
        </ElTableColumn>
        <template #empty>
          <ElEmpty />
        </template>
      </ElTable>
      <ElPagination
        class="pagination"
        layout="sizes, prev, pager, next, jumper, total"
        :page-sizes="[20, 50, 100]"
        :default-page-size="20"
        :limit="listQuery.size"
        :page="listQuery.page"
        :total="listTotal"
        size="small"
        background
        @current-change="changePagination"
        @size-change="sizeChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.absent {
  width: 12px;
  height: 12px;
  background: #67c23a;
  border-radius: 2px;
  display: inline-block;
}
.absent-1 {
  background: #f56c6c;
}
</style>
